package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import edu.byu.intex2.data.GUID;
import edu.byu.intex2.data.bo.SaleLine;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 * SaleLine Data Access Object
 * @author Brady
 */
public class SaleLineDAO {

    /////////////////////////////////////////////
    ///   Singleton code
    private static SaleLineDAO instance = null;

    /** Creates a new instance of SaleLineDAO */
    private SaleLineDAO() {
    }//constructor

    /** Retrieves the single instance of this class */
    public static synchronized SaleLineDAO getInstance() {
        if (instance == null) {
            instance = new SaleLineDAO();
        }
        return instance;
    }//getInstance

    ////////////////////////////////////////////
    ///   CREATE methods
    /**
     * Creates a new saleLine in the database 
     * @param id GUID
     * @param VIN physical_car vin of sale line
     */
    public SaleLine create(String saleId, String vin) throws DataException {
        SaleLine saleLine = new SaleLine(GUID.generate()); // generate a guid for the salesLine even though we never use this...
        saleLine.setObjectAlreadyInDB(false);

        // Set Sale ID
        saleLine.setSaleId(saleId);

        // Set Physical Car
        try { saleLine.setPhysicalCar(PhysicalCarDAO.getInstance().getByVIN(vin)); } catch (Exception e){ e.printStackTrace(); }

        Cache.getInstance().put(saleLine.getId(), saleLine); // put in cache just in case...
        return saleLine;
    }//create


    ////////////////////////////////////////////
    ///   READ methods
    /**
     * Reads an existing saleLine from the database     */
    public SaleLine read(String id) throws DataException {
        // Check Cache
        if (Cache.getInstance().containsKey(id)) {
            return (SaleLine) Cache.getInstance().get(id);
        }

        // Get Connection
        Connection conn = ConnectionPool.getInstance().get();

        // Try Reading with connection
        try {
            return read(id, conn);
        } catch (Exception e) {
            throw new DataException("An error occurred while reading the SaleLine object information.", e);
        } finally {
            ConnectionPool.getInstance().release(conn);
        }
    }

    /**
     * Internal method to read an existing saleLine from the database
     * @return saleLine
     */
    synchronized SaleLine read(String id, Connection conn) throws Exception {
        // Check Cache
        if (Cache.getInstance().containsKey(id)) {
            return (SaleLine) Cache.getInstance().get(id);
        }

        // Prepare a SQL Statement
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM sale_line where id=?");

        try {
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery(); // execute query
            if (rs.next()) {
                // Read the record with the result set
                return readRecord(rs, conn);
            }//if
            throw new DataException("SaleLine with id '" + id + "' not found.");
        } finally {
            stmt.close();
        }
    }//read

    /** Internal method to create a saleLine object from a record  */
    synchronized SaleLine readRecord(ResultSet rs, Connection conn) throws Exception {
        if (Cache.getInstance().containsKey(rs.getString("id"))) {
            return (SaleLine) Cache.getInstance().get(rs.getString("id"));
        }
        // Create new saleLine object
        SaleLine saleLine = new SaleLine(rs.getString("id"));

        // SaleLine is already in DB
        saleLine.setObjectAlreadyInDB(true);

        // Put saleLine in cache
        Cache.getInstance().put(saleLine.getId(), saleLine);

        // Set SaleLine Attributes
        saleLine.setSaleId(rs.getString("sale_id"));
        saleLine.setPhysicalCarId(rs.getString("physical_car_id"));
        saleLine.setActualPrice(rs.getDouble("actual_price"));
        saleLine.setListPrice(rs.getDouble("list_price"));

        // SaleLine is dirty and needs to be saved to DB
        saleLine.setDirty(false);

        return saleLine;
    }//readRecord


    /////////////////////////////////////////////
    ///   UPDATE methods
    /** Saves an existing saleLine in the database */
    public void save(SaleLine saleLine) throws DataException {
        // get a connection from the pool, save all of the sales first using the other saleLine method and then commit them in the database
        Connection conn = ConnectionPool.getInstance().get();

        try {
            save(saleLine, conn); // save with connection
            conn.commit();  // commit the db transaction
        } catch (Exception e) {
            try {
                //rollback if there were any errors saving, catch any other errors you might have
                conn.rollback();
            } catch (SQLException e2) {
                throw new DataException("Could not roll back the saleLine database transaction!", e2);
            }
            throw new DataException("An error occurred while saving the saleLine object information.", e);
        } finally {
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }
    }

    /** Internal method to update a saleLine in the database */
    void save(SaleLine saleLine, Connection conn) throws Exception {
        // put the saleLine object to cache
        Cache.getInstance().put(saleLine.getId(), saleLine);

        // decide whether to update or insert into the database
        if (saleLine.isObjectAlreadyInDB() && saleLine.isDirty()) {
            update(saleLine, conn);
        } else if (saleLine.isDirty()) {
            insert(saleLine, conn);
        }//if
    }

    /** External method to update or create a saleLine in the database without committing connection */
    public void saveNoCommit(SaleLine saleLine, Connection conn) throws Exception {
        // Get Already in Databsae
         Boolean alreadyInDB = saleLine.isObjectAlreadyInDB();

        // decide whether to update or insert into the database
        if (alreadyInDB) {
            update(saleLine, conn);
        } else {
            insert(saleLine, conn);
        }

        // Save No Commit our pretty physical car
        PhysicalCarDAO.getInstance().saveNoCommit(saleLine.getPhysicalCar(), conn);

        // TODO: Set Lot to null
    }

    /** Saves an existing saleLine to the database */
    private void update(SaleLine saleLine, Connection conn) throws Exception {
        // use a prepared statement to prevent sql injection
        PreparedStatement stmt = conn.prepareStatement("UPDATE sale_line SET actual_price=?, list_price=?  WHERE sale_id=? AND physical_car_id=?");
        try {
            // Get SaleLine Attributes and add them to the statement
            stmt.setDouble(1, saleLine.getActualPrice());
            stmt.setDouble(2, saleLine.getListPrice());
            stmt.setString(3, saleLine.getSaleId());
            stmt.setString(4, saleLine.getPhysicalCarId());
            stmt.execute();

            // SaleLine is clean!
            saleLine.setDirty(false);
        } finally {
            stmt.close();  // make sure to close the prepared statement
        }
    }

    /** Inserts a new saleLine into the database */
    private void insert(SaleLine saleLine, Connection conn) throws Exception {
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO sale_line (sale_id, physical_car_id, actual_price, list_price) VALUES (?, ?, ?, ?)");
        try {
            // Set SaleLine Attributes
            stmt.setString(1, saleLine.getSaleId());
            stmt.setString(2, saleLine.getPhysicalCarId());
            stmt.setDouble(3, saleLine.getActualPrice());
            stmt.setDouble(4, saleLine.getListPrice());
            stmt.execute();

            saleLine.setObjectAlreadyInDB(true); // now in DB
            saleLine.setDirty(false); // object is clean
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stmt.close(); // close the prepared statement
        }
    }

    /////////////////////////////////////////////////
    ///   DELETE methods
    /** We do not support deleting of business objects in this application */
    public void delete(SaleLine saleLine) throws DataException {
        throw new RuntimeException("Nice try. The delete function is not supported in this application.");
    }

    ////////////////////////////////////////////////
    ///   SEARCH methods

}
